package com.nontax.test.util;

import com.alibaba.fastjson.JSON;
import com.nontax.test.common.domain.PaymentRestRequest;
import com.nontax.test.common.domain.PaymentRestResponse;
import com.nontax.test.common.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;

@Slf4j
public class OldRestCilent {

    private static Charset charset = Charset.forName("utf-8");
//    private static String token = "BS_NONTAX_TOKEN";

    public static void  callOldInterface(String url,Object obj,String token,String sid) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        String json = Base64Util.encodeBase64String(JSON.toJSONString(obj));
        String noise = Long.toString(new Date().getTime());
        String sign = SignUtil.sign(token, json, noise);

        PaymentRestRequest request = new PaymentRestRequest();
        request.setData(json);
        request.setNoise(noise);
        request.setSign(sign);
        String reqJson = JSON.toJSONString(request);
        WebSocketServer.sendInfo("请求参数为:"+reqJson,sid);
        HttpEntity entity = new StringEntity(reqJson);
        post.setEntity(entity);
        HttpResponse response = null;
        try {
            response = client.execute(post);
        }catch (Exception e){
            e.printStackTrace();
        }
        HttpEntity responseEntity = response.getEntity();

        String result = IOUtils.toString(responseEntity.getContent());
		PaymentRestResponse comm =  JSON.parseObject(result,PaymentRestResponse.class);
		WebSocketServer.sendInfo("对方返回:"+result,sid);
		// 校验sign 6ee4fc8a07514c34a4291041a90ad846
		String check = SignUtil.sign(token, comm.getData(), comm.getNoise());
		if(!check.equals(comm.getSign())){
            WebSocketServer.sendInfo("签名校验失败",sid);
			log.debug("签名校验失败");
		}
		byte [] paramByte = Base64.decodeBase64(comm.getData());
		String resData = new String(paramByte,charset);
        WebSocketServer.sendInfo("服务方返回业务数据为:"+resData,sid);
    }
}
